/*
 *  Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package ru.apertum.qsystem.client.forms;

import javax.swing.JFrame;
import javax.swing.ListModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;
import ru.apertum.qsystem.QSystem;
import ru.apertum.qsystem.common.Uses;import ru.apertum.qsystem.common.QLog;
import ru.apertum.qsystem.server.model.ISailListener;
import ru.apertum.qsystem.server.model.QService;
import ru.apertum.qsystem.server.model.QServiceTree;
import ru.apertum.qsystem.server.model.QUser;

/**
 * Created on 16.10.2009, 19:35:45
 * @author Evgeniy Egorov
 */
public class FMessager extends javax.swing.JDialog {

    /** Creates new form FMessager
     * @param parent
     * @param modal
     * @param port
     * @param users
     * @param services
     */
    public FMessager(java.awt.Frame parent, boolean modal, int port, ListModel users, TreeModel services) {
        super(parent, modal);
        initComponents();
        this.port = port;
        listUsers.setModel(users);
        treeServices.setModel(services);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        checkBoxAll = new javax.swing.JCheckBox();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        listUsers = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        treeServices = new javax.swing.JTree();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TextAreaMessage = new javax.swing.JTextArea();
        ButtonSend = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.apertum.qsystem.QSystem.class).getContext().getResourceMap(FMessager.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel1.setBorder(new javax.swing.border.MatteBorder(null));
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        checkBoxAll.setText(resourceMap.getString("checkBoxAll.text")); // NOI18N
        checkBoxAll.setName("checkBoxAll"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 160, Short.MAX_VALUE)
                .addComponent(checkBoxAll)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(checkBoxAll))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSplitPane1.setDividerLocation(155);
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        listUsers.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("listUsers.border.title"))); // NOI18N
        listUsers.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        listUsers.setName("listUsers"); // NOI18N
        jScrollPane2.setViewportView(listUsers);

        jSplitPane1.setLeftComponent(jScrollPane2);

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        treeServices.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("treeServices.border.title"))); // NOI18N
        treeServices.setName("treeServices"); // NOI18N
        jScrollPane3.setViewportView(treeServices);

        jSplitPane1.setRightComponent(jScrollPane3);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel2.border.title"))); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        TextAreaMessage.setColumns(20);
        TextAreaMessage.setRows(5);
        TextAreaMessage.setName("TextAreaMessage"); // NOI18N
        jScrollPane1.setViewportView(TextAreaMessage);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
        );

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(ru.apertum.qsystem.QSystem.class).getContext().getActionMap(FMessager.class, this);
        ButtonSend.setAction(actionMap.get("sendMessage")); // NOI18N
        ButtonSend.setText(resourceMap.getString("ButtonSend.text")); // NOI18N
        ButtonSend.setName("ButtonSend"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(209, Short.MAX_VALUE)
                .addComponent(ButtonSend)
                .addContainerGap())
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ButtonSend)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    /**
     * Используемая ссылка на диалоговое окно.
     */
    private static FMessager messagerForm;
    private final int port;

    private static ResourceMap localeMap = null;

    private static String getLocaleMessage(String key) {
        if (localeMap == null) {
            localeMap = Application.getInstance(QSystem.class).getContext().getResourceMap(FMessager.class);
        }
        return localeMap.getString(key);
    }

    /**
     * Выбор услуги для перенаправления.
     * @param port
     * @param users
     * @param services
     * @param owner относительно этого контрола модальность и позиционирование
     */
    public static void getMessager(JFrame owner, int port, ListModel users, TreeModel services) {
        QLog.l().logger().info("Выбор услуги для перенаправления.");
        if (messagerForm == null) {
            messagerForm = new FMessager(owner, true, port, users, services);
        }
        messagerForm.setLocation(Math.round(owner.getLocation().x + owner.getWidth() / 2 - messagerForm.getWidth() / 2),
                Math.round(owner.getLocation().y + owner.getHeight() / 2 - messagerForm.getHeight() / 2));
        messagerForm.setVisible(true);
    }
    private static String s = "message#";

    @Action
    public void sendMessage() {
        s = "message#";
        if (checkBoxAll.isSelected()) {
            s = s + "ALL";
        } else {
            for (Object o : listUsers.getSelectedValuesList()) {
                s = s + "@" + ((QUser)o).getId().toString() + "@";
            }
            if (treeServices.getSelectionPaths() != null) {
                for (Object o : treeServices.getSelectionPaths()) {
                    final TreePath selectedPath = (TreePath) o;
                    final QService service = (QService) selectedPath.getLastPathComponent();

                    QServiceTree.sailToStorm(service, new ISailListener() {

                        @Override
                        public void actionPerformed(TreeNode service) {
                            s = s + "@" + ((QService)service).getId().toString() + "@";
                        }
                    });
                }
            }
        }
        Uses.sendUDPBroadcast(s + "##" + TextAreaMessage.getText(), port);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonSend;
    private javax.swing.JTextArea TextAreaMessage;
    private javax.swing.JCheckBox checkBoxAll;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JList listUsers;
    private javax.swing.JTree treeServices;
    // End of variables declaration//GEN-END:variables
}
